package com.gobang.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gobang.domain.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * JWT权限不足处理器
 * 当用户认证成功但权限不足时，返回统一的JSON响应
 */
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        log.warn("权限不足: URI={}, 用户={}, 错误={}", 
                request.getRequestURI(), 
                request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : "匿名",
                accessDeniedException.getMessage());

        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        // 构造统一响应格式
        Result<Void> result = Result.fail(403, "权限不足，无法访问该资源");

        // 写入响应
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}

